/**   
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package etrl.resources;

import com.google.gwt.event.dom.client.ErrorEvent;
import com.google.gwt.event.dom.client.ErrorHandler;
import com.google.gwt.event.dom.client.LoadEvent;
import com.google.gwt.event.dom.client.LoadHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.RootPanel;
import com.googlecode.gwtgl.binding.WebGLRenderingContext;
import com.googlecode.gwtgl.binding.WebGLTexture;

/**
 * \class TextureResource
 * \brief Specialized AResource to manage texture resource
 * @author harold
 *
 */
public class TextureResource extends AResource implements LoadHandler, ErrorHandler
{
	/**
	 * GL texture object
	 */
	private	WebGLTexture _texture = null;
	
	/**
	 * GL context
	 */
	private WebGLRenderingContext _gl = null;
	
	/**
	 * Image object used to get pixels data
	 */
	private Image _img = null;
	
	/**
	 * Flag to generate mipmaps or not
	 */
	private boolean _generateMipmap;
	
	/**
	 * \brief Initializes the texture ressource
	 * @param[in] gl current gl context object
	 * @param[in] filePath file path of the texture
	 * @param[in] generateMipmap flag to generate or not mipmaps for this texture
	 */
	protected TextureResource(WebGLRenderingContext gl, String filePath, boolean generateMipmap)
	{
		super(filePath);
		_gl = gl;
		_generateMipmap = generateMipmap;
		
		// Create the image and the texture object
		_img = new Image(getFilePath());
		_texture = _gl.createTexture();		
	}

	
	public Image getImage(){
		return _img;
	}
	
	/**
	 * \brief Loads the texture
	 */
	
	public void load()
	{
		// Add the image to root panel to be able to get the image pixels data
		// TODO : check for another way to do it ... its ugly
		RootPanel.get().add(_img);
			
		// As we do not want to see the image, hide it
		_img.setVisible(false);
			
		// And add the load handler to detect the image load end
		_img.addLoadHandler(this);
		
		// And add the error handler to detect loading errors
		_img.addErrorHandler(this);
	}

	/**
	 * \brief Loader method called when the image data has been loaded succesfuly
	 * @param[in] event Load event
	 */
	
	public void onLoad(LoadEvent event)
	{		
		// Now we can remove the image from panel
		RootPanel.get().remove(_img);

		// Set the data of the gl texture object
			// Set current texture object as active
		_gl.bindTexture(WebGLRenderingContext.TEXTURE_2D,_texture);
		
			// As opengl texture conventions about image origin is inversed on Y axis compared to OS image convention
			// we have to flip the Y axis of the image
		_gl.pixelStorei(WebGLRenderingContext.UNPACK_FLIP_Y_WEBGL, 1);
		
			// And finaly, set the image pixels data in the texture object
		_gl.texImage2D(WebGLRenderingContext.TEXTURE_2D, 0, WebGLRenderingContext.RGBA, WebGLRenderingContext.RGBA, WebGLRenderingContext.UNSIGNED_BYTE, _img.getElement());
			
		// If generating mipmap is requested, parameter the texture filtering to using them and generate mipmaps ...
		if(_generateMipmap)
		{
			_gl.texParameteri(WebGLRenderingContext.TEXTURE_2D, WebGLRenderingContext.TEXTURE_MAG_FILTER, WebGLRenderingContext.LINEAR);
			_gl.texParameteri(WebGLRenderingContext.TEXTURE_2D, WebGLRenderingContext.TEXTURE_MIN_FILTER, WebGLRenderingContext.LINEAR_MIPMAP_NEAREST);
			_gl.generateMipmap(WebGLRenderingContext.TEXTURE_2D);
		}
		else // else do not use mipmap
		{
			_gl.texParameteri(WebGLRenderingContext.TEXTURE_2D, WebGLRenderingContext.TEXTURE_MAG_FILTER, WebGLRenderingContext.LINEAR);
			_gl.texParameteri(WebGLRenderingContext.TEXTURE_2D, WebGLRenderingContext.TEXTURE_MIN_FILTER, WebGLRenderingContext.LINEAR);
		}

		// Finaly unbind the texture object
		_gl.bindTexture(WebGLRenderingContext.TEXTURE_2D, null);
		
		// The texture has been loaded successfuly
		iAmLoaded(true);
	}
	
	/**
	 * \brief Loader method called if an error occured while texture loading.
	 * @param[in] event Error event
	 */
	
	public void onError(ErrorEvent event)
	{		
    	// An error occured
		iAmLoaded(false);
	}
	
	/**
	 * \brief GL Texture object id getter
	 * @return object id
	 */
	WebGLTexture getTextureObjectId()
	{
		return _texture;
	}

	/**
	 * \brief On resource release, delete the texture object
	 */
	
	public void onRelease()
	{
		if(_texture != null)
		{
			_gl.deleteTexture(_texture);
		}
	}
}
